package work.jame.dynamic.core;

import org.springframework.aop.Advisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import work.jame.dynamic.aop.DynamicDataSourceAnnotationAdvisor;
import work.jame.dynamic.aop.DynamicDataSourceAnnotationInterceptor;
import work.jame.dynamic.config.DynamicDataSourceConfig;

import javax.sql.DataSource;

/**
 * @author : Jame
 * @date : 2023-11-25 10:20
 **/

@Configuration
public class AutoHandler {

    @Autowired
    private DynamicDataSourceConfig config;

    @Bean
    public DataSource abstractRoutingDataSource() {
        return new RoutingDataSource(config);
    }


    @Bean
    public Advisor dynamicDataSourceAnnotationAdvisor() {
        DynamicDataSourceAnnotationInterceptor interceptor = new DynamicDataSourceAnnotationInterceptor(config.getDefaultDataSourceKey());
        DynamicDataSourceAnnotationAdvisor advisor = new DynamicDataSourceAnnotationAdvisor(interceptor);
        advisor.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return advisor;
    }
}
